import { useState } from "react";
import type { Position } from "../types/position";

export function useGeolocation() {
  const [isLoading, setIsLoading] = useState<boolean>(true);
  // 使用 useState 钩子定义 position 状态，初始值为 { latitude: 0, longitude: 0 }
  // position: 当前地理位置对象，包含纬度（latitude）和经度（longitude）
  // setPosition: 用于更新 position 状态的函数
  const [position, setPosition] = useState<Position>({
    latitude: 0,
    longitude: 0,
  }); // 初始位置设为 (0, 0)

  async function getCurrentLocation(): Promise<void> {
    return new Promise((resolve, reject) => {
      setIsLoading(true);

      if (!navigator.geolocation) {
        setIsLoading(false);
        reject("Your browser does not support geolocation");
      }

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;

          setIsLoading(false);
          setPosition({ latitude, longitude });
          resolve();
        },
        (error) => {
          setIsLoading(false);
          reject(error.message);
        }
      );
    });
  }

  return { getCurrentLocation, position, isLoading };
}
